<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="4" :collapse="false" :isSubmitBtn="false"></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partPartOtherPartObliIndex"
      :onCellChange="changeQuantity"
      :dataSource="tableSource"
      :isMemoryPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="val => (this.tableForm = val)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>
    <div class="btnWrap">
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="closeDrawer(2)">保 存</el-button>
    </div>

    <BaseDialog :visible.sync="visible1" title="配件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '120px' }">
      <salesOrderAdd @close="closeHandler1" @changedata="changedata" />
    </BaseDialog>
  </div>
</template>
<script>
import add from './tabs/add';
import salesOrderAdd from './salesOrderAdd';
import { queryPartObligatedItem, performExecute, performExecutes, querys } from '@/api/part/partOther/partObli';
import _ from 'lodash';
import { confirmAction, notifyAction, jsonToHump } from '@/utils';

export default {
  components: {
    add,
    salesOrderAdd
  },
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createColums(),
      btnDisabled: false,
      visible1: false,
      tableSource: [],
      tableForm: []
    };
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '预留单号',
          fieldName: 'obligatedNo',
          disabled: true,
          placeholder: '请选择'
          // unitRender: () => {
          //   return (
          //     <div>
          //       <el-button slot="append" icon="el-icon-search" disabled={this.yuliudan} onClick={() => this.searchAll()}></el-button>
          //     </div>
          //   );
          // }
        }
      ];
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        this.hold();
      }
    },
    delete(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.itemId) {
          this.itemIds = this.itemIds + ',' + row.itemId;
        }
        this.$refs.table.EXECUTE_DELETE([row]);
        this.btn1 = false;
      });
    },
    addHandle() {
      this.visible1 = true;
    },
    closeHandler1() {
      this.visible1 = false;
    },
    changeQuantity(val1, val2) {
      if (Number(val2.useableStock) < Number(val2.quantity)) {
        return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
      }
      // val2.costAmount = val2.costPrice * val2.quantity;
    },
    changedata(val) {
      console.log(val, 'changedata::');
      let res = _.cloneDeep(val);
      // res.COST_AMOUNT = res.COST_PRICE * res.LOCKED_QUANTITY;
      jsonToHump(res);
      res.quantity = res.lockedQuantity;
      let flag = true;
      this.tableForm.forEach(x => {
        if (x.partNo == res.partNo) {
          flag = false;
        }
      });
      if (flag) {
        this.$refs.table.EXECUTE_INSERT(res);
        console.log(' this.tableForm', this.tableForm);
        this.$notify.success({ title: '提示信息', message: '添加成功' });
      } else {
        this.$notify.warning({ title: '提示信息', message: '配件已存在' });
      }
    },
    // 预留
    hold() {
      if (this.tableForm.length <= 0) {
        this.$notify.warning({ title: '提示信息', message: '请插入预留的配件！' });
        return;
      }
      let rr = _.cloneDeep(this.tableForm);
      rr.forEach(x => {
        x.isObligated = 10041001;
      });
      this.$confirm('是否确定保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let obj = {
          obligatedNo: this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue || '',
          // applicant: this.topFilterList.find(item => item.fieldName === 'applicant').initialValue || '',
          // owenNo: this.topFilterList.find(item => item.fieldName === 'ownerNo').initialValue || '',
          // ownerName: this.topFilterList.find(item => item.fieldName === 'ownerName').initialValue || '',
          // license: this.topFilterList.find(item => item.fieldName === 'license').initialValue || '',
          // remark: this.topFilterList.find(item => item.fieldName === 'remark').initialValue || '',
          // itemIds: this.itemIds || '',
          tables: rr,
          // 模块区分
          ptype: this.ptype ? this.ptype : null
        };
        let a = true;
        // console.log(obj, '----obj----');
        // let a = (this.btnDisabled = true);
        // this.columns.find(x => x.dataIndex === 'quantity').disabled = true;
        if (rr.length == 0) {
          a = false;
          return this.$notify.warning({ title: '提示信息', message: '请添加需要预留的配件！' });
        }
        rr.forEach(x => {
          // 增加预留数量判断
          if (x.quantity <= 0) {
            a = false;
            return this.$notify.warning({ title: '提示信息', message: '请输入预留数量！' });
          }
          if (Number(x.useableStock) < Number(x.quantity)) {
            a = false;
            return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
          }
        });
        if (a) {
          this.getperformExecutes(obj);
        }
        // debugger;
      });
    },
    async getperformExecutes(val) {
      const res = await performExecutes(val);
      this.obligatedNo = res.data.obligatedNo;
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '预留成功！' });
        this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue = this.obligatedNo;
        this.$emit('close', false);
        // let res = await queryPartObligatedItem({ obligatedNo: this.obligatedNo });
        // this.dataSource = res.data;
        // this.topFilterList.find(item => item.fieldName === 'applicant').disabled = true;
        // this.btn = this.btn1 = true;
        // this.btn2 = false;
      }
    },
    createColums() {
      return [
        {
          title: '序号',
          dataIndex: 'indexaa',
          width: 90,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.btnDisabled} onClick={() => this.delete(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预留数量',
          dataIndex: 'quantity',
          // disabled: false,
          precision: 2,
          editable: true,
          // min: 1,
          editType: 'number',
          editPattern: /^(?!0\d|[0.]+$)\d+(\.\d{2})?$/,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'useableStock',
          disabled: true,
          precision: 2,
          // min: 1,
          editType: 'number',
          editPattern: /^(?!0\d|[0.]+$)\d+(\.\d{2})?$/,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'stockQuantity',
          disabled: true,
          precision: 2,
          // min: 1,
          editType: 'number',
          editPattern: /^(?!0\d|[0.]+$)\d+(\.\d{2})?$/,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本单价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
          // render: props => {
          //   return <span>{props.row.costPrice}</span>;
          // }
        },
        {
          title: '含税成本金额',
          dataIndex: 'costAmount',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.costAmount}</span>;
          // }
        }
      ];
    }
  }
};
</script>
<style lang="less" scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
